package com.neusoft.neu24.mybatis01.util;

import com.neusoft.neu24.mybatis01.entity.Point;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedJdbcTypes(JdbcType.VARCHAR)
public class PointTypeHandler extends BaseTypeHandler<Point> {

//    把point对象转化为Stirng ，后放入数据库中
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Point parameter, JdbcType jdbcType) throws SQLException {
        // 把Point对象转换成字符串
        String pointStr = parameter.getX() + "," + parameter.getY();
        ps.setString(i, pointStr);

    }

    @Override
//    1,2
    public Point getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String pointStr = rs.getString(columnName);
        return  toPoint(pointStr);
    }

    @Override
    public Point getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String pointStr = rs.getString(columnIndex);
        return  toPoint(pointStr);

    }

    private Point toPoint(String pointStr) {
        String[] split = pointStr.split(",");
        int x =   Integer.parseInt( split[0]);
        int y =   Integer.parseInt( split[1]);
        return  new Point(x,y) ;
    }

    @Override
    public Point getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return null;
    }
}
